package com.example.guiguiapplicatio.fragment.record;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.guiguiapplicatio.api.GetRecordApi;
import com.example.guiguiapplicatio.api.Interface.GetRecordCallback;
import com.example.guiguiapplicatio.api.Interface.SearchRecordCallback;
import com.example.guiguiapplicatio.api.SearchRecordApi;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.databinding.FragmentRecordBinding;
import com.example.guiguiapplicatio.fragment.record.adapter.RecordFragmentAdapter;
import com.example.guiguiapplicatio.placeholder.RecordPlaceholderContent;
import com.example.guiguiapplicatio.placeholder.RecordPlaceholderContent.PlaceholderItem;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.guiguiapplicatio.Response.Record;

public class RecordFragment extends Fragment implements GetRecordCallback, SearchRecordCallback {
    FragmentRecordBinding binding;
    RecordFragmentAdapter adapter;

    private GetRecordApi getRecordApi;
    private SearchRecordApi searchRecordApi;
    public static List<PlaceholderItem> NOW_ITEMS = new ArrayList<PlaceholderItem>();
    private TabHost tabHost;
    private int SHOW_SIFT = 0;

    private ArrayList<String> searthList = new ArrayList<String>();
    private CheckBox[] checkBoxes;
    private ArrayList<String> tmpSelectedId1 = new ArrayList<String>();
    private ArrayList<String> tmpSelectedId2 = new ArrayList<String>();
    private Map<String, Boolean> tmpSelectedId3;
    private String idNamePhone = "-1";
    private Integer recordTotal;
    private Integer recordSearchCount;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentRecordBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        binding.recordList.setLayoutManager(new LinearLayoutManager(binding.getRoot().getContext()));
        NOW_ITEMS = RecordPlaceholderContent.ITEMS;
        adapter = new RecordFragmentAdapter(NOW_ITEMS, getContext());
        binding.recordList.setAdapter(adapter);

        getRecordApi = new GetRecordApi(this);

        getRecordApi.setGetRecordCallback(this);

        getRecordApi.performGetRecordList();

        searchRecordApi = new SearchRecordApi(this);
        searchRecordApi.setSearchRecordCallback(this);


        checkBoxes = new CheckBox[]{
                view.findViewById(R.id.gaoxueya),
                view.findViewById(R.id.gaoxuetang),
                view.findViewById(R.id.gaoxuezhi),
                view.findViewById(R.id.ertong),
                view.findViewById(R.id.laoren)
        };
        tmpSelectedId3 = new HashMap<>();
        // 初始化复选框状态的 Map，所有复选框默认为未选中状态
        for (CheckBox checkBox : checkBoxes) {
            String text = checkBox.getText().toString();
            tmpSelectedId3.put(text, false);
        }
        siftTrains();

        binding.searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchClear();
                SHOW_SIFT = 0;
                idNamePhone = "-1";
                binding.tabhost.setVisibility(View.INVISIBLE);
                String searchText = binding.etSearchtext.getText().toString();
                if (!searchText.isEmpty()) {
                    idNamePhone = searchText;
                }
                Integer sstatus = -1;
                String ssex = "-1";
                Integer sage = -1;
                List<String> listenerNames = new ArrayList<>();
                searchRecordApi.performSearchRecordList(sstatus, ssex, sage, idNamePhone, listenerNames);
            }
        });
        binding.servicBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
        return view;
    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
//        getRecordApi.performGetRecordList();
    }

    @Override
    public void onSuccess(ResponseBody<List<Record>> responseBody) {
        Object data = responseBody.getData();
        if (data instanceof List) {
            List<Record> records = (List<Record>) data;
            recordTotal=records.get(0).getRecordTotal();
            recordSearchCount=records.get(0).getRecordSearchCount();
            // 清空原有的占位符项列表
            NOW_ITEMS.clear();
//            RecordPlaceholderContent.ITEMS.clear();
            // 将每个记录对象转换为占位符项，并添加到列表中
            for (Record record : records) {
//                recordTotal = record.getRecordTotal();
//                recordSearchCount = record.getRecordSearchCount();
                RecordPlaceholderContent.addItem(new RecordPlaceholderContent.PlaceholderItem(
                        record.getIdcard(),
                        record.getName(),
                        record.getSex(),
                        record.getAge(),
                        record.getDetailedresidence(),
                        record.getListenername(),
                        record.getPhone(),
                        record.getStatus(),
                        record.getRecordTotal(),
                        record.getRecordSearchCount()
                ));
            }

            Log.d("info", "Total items: " + RecordPlaceholderContent.ITEMS.size());
            if (getActivity()!=null){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.recordTotal.setText("档案总数："+recordTotal);
                        binding.recordSearch.setText("已筛选数："+recordSearchCount);
                    }
                });
            }

            // 通知适配器数据已更改
            adapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onFailure(String errorMessage) {
        if (getActivity()!=null){
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), "档案列表响应失败", Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

    @Override
    public void onSearchSuccess(ResponseBody<List<Record>> responseBody) {
        Object data = responseBody.getData();
        if (data instanceof List) {
            Log.d("info", data.toString());
            List<Record> records = (List<Record>) data;
            if (records.isEmpty()) {
                List<String> listenerNames = new ArrayList<>();
                searchRecordApi.performSearchRecordList(-1, "-1", -1, "-1", listenerNames);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "没有符合条件的数据", Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                recordSearchCount = records.get(0).getRecordSearchCount();
                // 清空原有的占位符项列表
                NOW_ITEMS.clear();
//            RecordPlaceholderContent.ITEMS.clear();

                // 将每个记录对象转换为占位符项，并添加到列表中
                for (Record record : records) {
                    RecordPlaceholderContent.addItem(new RecordPlaceholderContent.PlaceholderItem(
                            record.getIdcard(),
                            record.getName(),
                            record.getSex(),
                            record.getAge(),
                            record.getDetailedresidence(),
                            record.getListenername(),
                            record.getPhone(),
                            record.getStatus(),
                            record.getRecordTotal(),
                            record.getRecordSearchCount()
                    ));
                }
                Log.d("info", "Total items: " + RecordPlaceholderContent.ITEMS.size());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.recordSearch.setText("已筛选数：" + recordSearchCount);
                    }
                });
                // 通知适配器数据已更改
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onSearchFailure(String errorMessage) {
        if (getActivity()!=null){
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), "档案列表响应失败", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void siftTrains() {
        binding.tabhost.setVisibility(View.INVISIBLE);
        tabHost = binding.tabhost;
        tabHost.setup();
        TabHost.TabSpec myTab1 = tabHost.newTabSpec("签约状态");
        myTab1.setIndicator("签约状态");
        myTab1.setContent(R.id.record_time_group);
        tabHost.addTab(myTab1);

        TabHost.TabSpec myTab2 = tabHost.newTabSpec("性别年龄");
        myTab2.setIndicator("性别年龄");
        myTab2.setContent(R.id.record_sex_age_group);
        tabHost.addTab(myTab2);

        TabHost.TabSpec myTab3 = tabHost.newTabSpec("人群分类");
        myTab3.setIndicator("人群分类");
        myTab3.setContent(R.id.scroll_view);
        tabHost.addTab(myTab3);

        binding.imgBtnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SHOW_SIFT == 0) {
                    SHOW_SIFT = 1;
                    binding.tabhost.setVisibility(View.VISIBLE);
                } else {
                    SHOW_SIFT = 0;
                    binding.tabhost.setVisibility(View.INVISIBLE);
                }

            }
        });
        binding.recordTimeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = group.findViewById(checkedId);
                tmpSelectedId1.clear();
                if (radioButton != null) {
                    String text = radioButton.getText().toString();
                    tmpSelectedId1.add(text);
                } else {
                    tmpSelectedId1.add("-1");
                }
                siftAndRemake();
            }
        });
        binding.recordSexAgeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = group.findViewById(checkedId);
                tmpSelectedId2.clear();
                if (radioButton != null) {
                    String text = radioButton.getText().toString();
                    tmpSelectedId2.add(text);
                } else {
                    tmpSelectedId2.add("-1");
                }
                siftAndRemake();
            }
        });
        CompoundButton.OnCheckedChangeListener checkBoxListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String text = buttonView.getText().toString();
                tmpSelectedId3.put(text, isChecked);
                siftAndRemake();
            }

        };
        for (CheckBox checkBox : checkBoxes) {
            checkBox.setOnCheckedChangeListener(checkBoxListener);
        }
    }

    private void siftAndRemake() {
        binding.searchSift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searthList.clear();
                String age = binding.edtAge.getText().toString();
                if (tmpSelectedId2.isEmpty()) {
                    tmpSelectedId2.add("-1");
                }
                if (tmpSelectedId1.isEmpty()) {
                    tmpSelectedId1.add("-1");
                }
                if (!age.isEmpty()) {
                    tmpSelectedId2.add(age);
                } else {
                    tmpSelectedId2.add("-1");
                }
                idNamePhone = "-1";
                searthList.addAll(tmpSelectedId1);
                searthList.addAll(tmpSelectedId2);
                searthList.add(idNamePhone);
                for (Map.Entry<String, Boolean> entry : tmpSelectedId3.entrySet()) {
                    if (entry.getValue()) { // 只添加选中的复选框文本
                        searthList.add(entry.getKey());
                    }
                }
                //                调整数据
                Log.d("info", searthList.toString());

                Integer sstatus = -1;
                String ssex = "-1";
                Integer sage = -1;
                List<String> listenerNames = new ArrayList<>();
                for (int i = 0; i < searthList.size(); i++) {
                    String item = searthList.get(i);
                    if (i == 0) {
                        // 如果是状态，则设置对应的状态值
                        if ("已签约".equals(item)) {
                            sstatus = 1;
                        } else if ("已过期".equals(item)) {
                            sstatus = 2;
                        } else if ("待签约".equals(item)) {
                            sstatus = 0;
                        }
                    } else if (i == 1) {
                        // 如果是性别，则直接赋值
                        ssex = item;
                    } else if (i == 2) {
                        // 如果是年龄，则尝试解析为整数
                        try {
                            sage = Integer.parseInt(item);
                        } catch (NumberFormatException e) {
                            // 解析失败则不设置年龄值
                            sage = -1;
                        }
                    } else if (i == 3) {
                        idNamePhone = "-1";
                    } else {
                        // 如果是其他监听者名称，则添加到列表中
                        listenerNames.add(item);
                    }
                }
                Log.d("info", "Status: " + sstatus);
                Log.d("info", "Sex: " + ssex);
                Log.d("info", "Age: " + sage);
                Log.d("info", "idNamePhone: " + idNamePhone);
                Log.d("info", "Listener Names: " + listenerNames);
                searchRecordApi.performSearchRecordList(sstatus, ssex, sage, idNamePhone, listenerNames);
                //                调整数据
                SHOW_SIFT = 0;
                binding.tabhost.setVisibility(View.INVISIBLE);
                searchClear();

            }
        });
        binding.searchRemake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchClear();
                List<String> listenerNames = new ArrayList<>();
                searchRecordApi.performSearchRecordList(-1, "-1", -1, "-1", listenerNames);
            }
        });
    }

    private void searchClear() {
        searthList.clear();
        tmpSelectedId1.clear();
        tmpSelectedId2.clear();
        tmpSelectedId3.clear();
        binding.edtAge.setText("");
        binding.recordTimeGroup.clearCheck();
        binding.gaoxueya.setChecked(false);
        binding.gaoxuetang.setChecked(false);
        binding.gaoxuezhi.setChecked(false);
        binding.ertong.setChecked(false);
        binding.laoren.setChecked(false);
        binding.recordSexAgeGroup.clearCheck();
    }
}